package com.dycx.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dycx.common.IPUtils;
import com.dycx.common.RestResponse;
import com.dycx.common.context.UserInfoContext;
import com.dycx.common.enums.BizTypeEnum;
import com.dycx.common.enums.SourceEnum;
import com.dycx.system.converter.LogConverter;
import com.dycx.system.dto.LogCreateDTO;
import com.dycx.system.mapper.LogMapper;
import com.dycx.system.dto.LogDTO;
import com.dycx.system.entity.LogDO;
import com.dycx.system.service.LogService;
import com.dycx.system.vo.LogVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@AllArgsConstructor
public class LogImpl extends ServiceImpl<LogMapper, LogDO> implements LogService {

    private LogMapper logMapper;

    @Override
    public Page<LogVO> getPage(LogDTO dto) {
        Page<LogVO> page = new Page<>(dto.getPageIndex(), dto.getPageSize());  // 查询第1页，每页返回5条

        Page<LogVO> voPage = logMapper.getPage(page, dto);
        voPage.getRecords().forEach(item -> {
            item.setBizTypeName(BizTypeEnum.converter(item.getBizType()));
            item.setSourceName(SourceEnum.converter(item.getSource()));
        });
        return voPage;
    }

    @Override
    public List<LogVO> getList(LogDTO dto) {
        LambdaQueryWrapper<LogDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getBizType()), LogDO::getBizType, dto.getBizType());
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getBizValue()), LogDO::getBizValue, dto.getBizValue());
        wrapper.orderByAsc(LogDO::getId);
        return LogConverter.entityToVoList(list(wrapper));
    }

    @Override
    public LogVO getInfoById(int logId) {
        LogDO logDO = this.getById(logId);
        return BeanUtil.toBean(logDO, LogVO.class);
    }

    @Override
    public void addLog(LogCreateDTO dto) {
        if (StrUtil.isNotBlank(dto.getPost()) && dto.getPost().length() > 5000) {
            dto.setPost(dto.getPost().substring(0, 5000));
        }

        LogDO logDO = new LogDO();
        logDO.setHost(dto.getRequest().getRequestURL().toString().replace(dto.getRequest().getRequestURI(), ""));
        logDO.setRoute(dto.getRequest().getRequestURI());
        logDO.setHeader(JSON.toJSONString(getHeaders(dto.getRequest())));
        logDO.setMethod(dto.getRequest().getMethod());
        logDO.setGet(dto.getRequest().getQueryString());
        logDO.setPost(dto.getPost());
        logDO.setResponse(JSON.toJSONString(dto.getResponse()));
        logDO.setIp(IPUtils.getIpAddr(dto.getRequest()));
        logDO.setSpeedTime(dto.getSpeedTime());
        logDO.setResult(dto.getResponse().isSuccess());
        logDO.setBizType(dto.getBizType());
        logDO.setBizValue(dto.getBizValue());
        logDO.setSource(Integer.parseInt(dto.getRequest().getHeader("source")));
        logDO.setLogTitle(dto.getLogTitle());
        logDO.setLogRemark(dto.getLogRemark());

        this.save(logDO);
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            headerMap.put(name, value);
        }
        return headerMap;
    }
}
